# -*- coding: utf-8 -*-
#   各种代理类
# @Time    ： 2024/4/24  14:36
# @Auther  ： 徐良
# File     :  delegates.py

# -*- coding: utf-8 -*-
#   基础的delegate
# @Time    ： 2023/1/30  17:46
# @Auther  ： 徐良
# File     :  baseDelegate.py

import re

from PySide6.QtWidgets import QStyledItemDelegate, QStyleOptionButton, QStyle, QApplication
from PySide6.QtCore import Qt, Signal, QModelIndex, QEvent
from PySide6.QtGui import QDoubleValidator, QIntValidator, QBrush, QColor
from share.baseFunction import quote, getListFormStrByVLine, getInstanceType
from share.colorFunction import getColorList
from share.sqlFunction import getSWO
from share.dataFactory import DataFactory
from share.mesEnum import *

class notEditDelegate(QStyledItemDelegate):
    """
    不运行被编辑， 没有颜色
    """
    def __init__(self, args):
        super(notEditDelegate, self).__init__()


    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

    def createEditor(self, parent, option, index):
        col = index.column()
        return None


class DelegateBase(QStyledItemDelegate):
    """
    基本类
    """
    mesDataChanged = Signal(QModelIndex)
    checkBoxSignal = Signal(QModelIndex)

    def __init__(self, args):
        super(DelegateBase, self).__init__()
        self.index = QModelIndex
        self.color = None
        self.statusFieldName = None
        self.colorGroup = None
        self.model = None
        self.selOption = 0
        self.colorGroup = ''
        self.enumClass = None
        self.initParaDict(args)

    def initParaDict(self, args):
        """
        初始化传参
        :param args:
        :return:
        """
        if 'model' in args:
            self.model = args['model']
        else:
            self.model = None

        if 'color' in args:
            self.color = args['color']
        else:
            self.color = None

        if 'selOption' in args:
            self.selOption = args['selOption']
        else:
            self.selOption = 0

        if 'statusFieldName' in args:
            self.statusFieldName = args['statusFieldName']
        else:
            self.statusFieldName = None

        if 'colorGroup' in args:
            self.colorGroup = args['colorGroup']
        else:
            self.colorGroup = None

        if 'enumClass' in args:
            self.enumClass = args['enumClass']

        if 'widgetList' in args:
            self.widgetList = args['widgetList']
        else:
            self.widgetList = []

        if self.model is not None:
            self.fieldList = self.model.fieldList

    def paint(self, painter, option, index):
        col = index.column()
        if self.widgetList[col] == 'check':  # check 方框
            check_style = QStyleOptionButton()
            check_style.rect = option.rect
            check_style.rect.setX(int(option.rect.x() + option.rect.width() / 2 - 6))
            if index.data() == 1:
                check_style.state = QStyle.State_Enabled | QStyle.State_On
            else:
                check_style.state = QStyle.State_Enabled | QStyle.State_Off
            QApplication.style().drawControl(QStyle.CE_CheckBox, check_style, painter)


        #---------------------------------------------------------------------------------
        # 要区分第1列的字段名是否为fsel,如果是fsel，则第1列不画背景色，否则要画
        col = index.column()
        if self.fieldList[0].lower() == 'fsel':
            condi = 1
        else:
            condi = 0
        if self.color == 1 and col >= condi:
            # 代理里只能设置背景色，字体颜色需要在model里设置
            brush = QBrush(Qt.SolidPattern)
            statusInt = self.getStatus(index.row())
            rect = option.rect
            back = getColorList(self.colorGroup, statusInt).split(',')
            brush.setColor(QColor(int(back[0]), int(back[1]), int(back[2]), int(back[3])))
            painter.fillRect(rect.x(), rect.y(), rect.width(), rect.height(), brush)

            return QStyledItemDelegate.paint(self, painter, option, index)
        else:
            if index.column() != 0:
                return QStyledItemDelegate.paint(self, painter, option, index)

    def editorEvent(self, e, model, option, index):
        # 只允许第0列可选
        col = index.column()
        # 要判断 第一个字段名是否为fsel, 有则执行该方法
        fsel = self.fieldList[col].lower()
        if fsel == 'fsel' and self.widgetList[col] == 'check':
            # 必须要加上e.type() == QEvent.MouseButtonPress，否则会执行两次
            if e.type() == QEvent.MouseButtonPress and e.button() == Qt.LeftButton:
                if index.data():
                    model.setData(index, 0)
                    self.checkBoxSignal.emit(index)
                else:
                    if self.selOption == 0:
                        if col == 0:
                            self.clearModelSel(model)
                        model.setData(index, 1)
                        self.checkBoxSignal.emit(index)
                    else:
                        model.setData(index, 1)
                        self.checkBoxSignal.emit(index)
        return True  # 表示事件已被处理

    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

    def clearModelSel(self, model):
        """
        置model中FSel字段为 0
        :return:
        """
        for i in range(0, model.rowCount()):
            index = model.index(i, 0)
            model.setData(index, 0)

    # ****************************    方法
    def getStatus(self, row):
        """
        获取model中状态字段的值
        :param row:
        :return:
        """
        val = self.model.record(row).value(self.statusFieldName)

        if val == '' or val is None:
            return 0
        if getInstanceType(val) == 'str':
            v = self.getEnumByName(val)
            return v

    def getEnumByName(self, sname):
        """
        获取状态枚举类的对应值
        :param sname:
        :return:
        """
        enum_class = globals()[self.enumClass]
        # 使用getattr()函数获取枚举常量值
        status_value = getattr(enum_class, sname).value
        return status_value

    def getFieldValue(self, idx):
        """
        获取model中指定列的值
        :param idx:
        :return:
        """
        if self.fieldList is None:
            return ''
        fn = self.fieldList[idx.column()]
        if self.model is not None and self.model.rowCount() > 0:
            return str(self.model.record(idx.row()).value(fn))
        else:
            return ''



class DelegateCheckColorNotEdit(DelegateBase):
    """
    有checkBox ,有颜色，不可编辑
    """
    def __init__(self, args):
        """
        调用父类初始化方法
        :param args:
        """
        super(DelegateCheckColorNotEdit, self).__init__(args)

    def paint(self, painter, option, index):

        super().paint(painter, option, index)  # 调用父类的 paint 方法并传递相同的参数

    def createEditor(self, parent, option, index):
        col = index.column()
        return None

    def editorEvent(self, e, model, option, index):
        # 调用父类的 editorEvent 方法，并获取其返回值
        super_return = super(DelegateCheckColorNotEdit, self).editorEvent(e, model, option, index)
        # 这里可以添加你自己的处理逻辑

        # 返回父类方法的返回值，如果父类方法返回了 None，则可以根据需要返回 True 或 False
        return super_return or False  # 如果父类方法返回了 None，则返回 False，表示事件未被处理




